const SwitchTabConfig = {
	INPUT_CLASS: 'switch-tab-input',
	ITEM_CLASS: 'switch-tab-item',
	ITEM_LABEL: 'switch-tab-label'
}

class SwitchTab {

	constructor(options) {
		this.container = document.querySelector(options.container);
		this.data = options.data || [];
		this.name = options.name || 'switch';
		this.currentIndex = options.currentIndex || 0;
		this.onChange = options.onChange || function() {}
		this.init();
		this.bindEvents();
	}

	init() {
		this.container.innerHTML = this.data.map((item, index) => {
			const checked = this.currentIndex === index ? 'checked' : '';
			const {
				key: id,
				label,
				value: num
			} = item;
			const bagde = num && parseInt(num) ? `<span class="badge">${num}</span>` : ``;
			return `<div class="${SwitchTabConfig.ITEM_CLASS}">
					<input type="radio" id="${id}" name="${this.name}-switch-tab" class="${SwitchTabConfig.INPUT_CLASS}"  ${checked} value="${id}" data-index="${index}">
					<label for="${id}" class="${SwitchTabConfig.ITEM_LABEL}">
						<div class="inner">
							${bagde}
							${item.label}
						</div>
					</label>
				</div>`
		}).join('');
	}

	bindEvents() {
		this.container.addEventListener('change', (e) => {
			if (e.target && e.target.matches(`.${SwitchTabConfig.INPUT_CLASS}`)) {
				let index = e.target.dataset.index;
				this.onChange(index)
			}
		});
	}

	updateData(newData) {
		this.data = newData;
		this.currentIndex = 0;
		this.init();
	}
}
